﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CaseManagerLibrary.Socket
{
    public class MessageBase
    {
        public const int HEAD_LENGTH = 4;
        public string Name { get; set; }

        public string from { get; set; }

        public string to { get; set; }

        public static byte[] Encode(MessageBase msg)
        {
            return Encode(JsonConvert.SerializeObject(msg));
        }
        public static byte[] Encode(string text)
        {
            byte[] data = null;
            try
            {
                byte[] body = System.Text.Encoding.UTF8.GetBytes(text);
                byte[] head = BitConverter.GetBytes(body.Length);

                data = new byte[head.Length + body.Length];
                Array.Copy(head, 0, data, 0, head.Length);
                Array.Copy(body, 0, data, head.Length, body.Length);
            }
            catch (Exception ex)
            { }
            return data;
        }

        public static string Decode(byte[] data)
        {
            string text = "";

            try
            {
                int bodyLen = BitConverter.ToInt32(data, 0);

                text = System.Text.Encoding.UTF8.GetString(data, HEAD_LENGTH, data.Length - HEAD_LENGTH);
            }
            catch (Exception ex)
            { }

            return text;
        }
    }
}
